package http_proxy_middleware

import (
	"gitee.com/zhoulvvv/my_go_gateway/dao"
	"gitee.com/zhoulvvv/my_go_gateway/middleware"
	"gitee.com/zhoulvvv/my_go_gateway/public"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"log"
	"time"
)

// HTTP QPS 统计
func HTTPFlowCountModeMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		serviceInterface, ok := c.Get("service")
		if !ok {
			middleware.ResponseError(c, 2001, errors.New("【服务不存在】service not found"))
			c.Abort()
			return
		}
		service := serviceInterface.(*dao.ServiceDetail)
		// 统计项： 1 全站 2 服务 3 租户
		// 全站统计器
		totalCounter, err := public.FlowCounterHandler.GetCounter(public.FlowTotal)
		if err != nil {
			middleware.ResponseError(c, 4001, errors.New("获取全站统计器失败："+err.Error()))
			c.Abort()
			return
		}
		totalCounter.Increase()
		dayCount, _ := totalCounter.GetDayData(time.Now())
		log.Printf("全站统计 qps:%v dayCount:%v", totalCounter.QPS, dayCount)
		// 服务统计器
		serviceCounter, err := public.FlowCounterHandler.GetCounter(public.FlowServicePrefix + service.Info.ServiceName)
		if err != nil {
			middleware.ResponseError(c, 4001, errors.New("获取服务统计器失败："+err.Error()))
			c.Abort()
			return
		}
		serviceCounter.Increase()
		dayServiceCount, _ := serviceCounter.GetDayData(time.Now())
		log.Printf("服务统计 qps:%v dayCount:%v", serviceCounter.QPS, dayServiceCount)
		c.Next()
	}
}
